package com.sys.object.common.utils;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import org.apache.commons.lang3.time.FastDateFormat;

public class UtilDate {
	public static String dateToChinese(String sDate, String DelimeterChar) {
		String[] tmpArr = sDate.split(DelimeterChar);
		String[] dArr = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
		for (int i = 0; i < 10; i++) {
			Integer x = Integer.valueOf(i);
			String temp = x.toString();
			tmpArr[0] = tmpArr[0].replaceAll(temp, dArr[i]);
		}
		tmpArr[0] = (tmpArr[0] + "年");
		if (tmpArr[1].length() == 1) {
			tmpArr[1] = (dArr[Integer.parseInt(tmpArr[1])] + "月");
		} else if (tmpArr[1].substring(0, 1).equals("0")) {
			tmpArr[1] = (dArr[Integer.parseInt(tmpArr[1].substring(
					tmpArr[1].length() - 1, tmpArr[1].length()))] + "月");
		} else {
			tmpArr[1] = ("十"
					+ dArr[Integer.parseInt(tmpArr[1].substring(
							tmpArr[1].length() - 1, tmpArr[1].length()))] + "月");
			tmpArr[1] = tmpArr[1].replaceAll("零", "");
		}

		if (tmpArr[2].length() == 1) {
			tmpArr[2] = (dArr[Integer.parseInt(tmpArr[2])] + "日");
		} else if (tmpArr[2].substring(0, 1).equals("0")) {
			tmpArr[2] = (dArr[Integer.parseInt(tmpArr[2].substring(
					tmpArr[2].length() - 1, tmpArr[2].length()))] + "日");
		} else {
			tmpArr[2] = (dArr[Integer.parseInt(tmpArr[2].substring(0, 1))]
					+ "十"
					+ dArr[Integer.parseInt(tmpArr[2].substring(
							tmpArr[2].length() - 1, tmpArr[2].length()))] + "日");
			tmpArr[2] = tmpArr[2].replaceAll("零", "");
		}

		return tmpArr[0] + tmpArr[1] + tmpArr[2];
	}

	public static String dateToString(Date date, String format) {
		String value = null;
		if (format.indexOf("-q") > 0) {
			value = month2quarter(date, format);
		} else {
			FastDateFormat df = FastDateFormat.getInstance(format);
			value = df.format(date);
		}
		return value;
	}

	public static String dateToString(Timestamp timestamp, String format) {
		return dateToString(timestamp, format);
	}

	protected static String month2quarter(Date date, String strFormat) {
		String value = null;

		if (strFormat.indexOf("-q") > 0) {
			FastDateFormat df = FastDateFormat.getInstance("yyyy-MM");
			value = df.format(date);

			int quarter = Integer.parseInt(value.substring(5)) / 3 + 1;
			value = value.substring(0, 5) + quarter;
		}

		return value;
	}

	public static String formatChineseDate(String strDate) {
		strDate = strDate.replaceAll("[日]", "");

		if (strDate.endsWith("月"))
			strDate = strDate.substring(strDate.length() - 1, strDate.length());
		if (strDate.endsWith("年"))
			strDate = strDate.substring(strDate.length() - 1, strDate.length());

		return strDate.replaceAll("[年,月]", "-");
	}

	public static String getDateFormat(String strDate) {
		String dateToken = null;
		String timeToken = null;
		try {
			if (strDate.indexOf("-") >= 0) {
				dateToken = "-";
			} else if (strDate.indexOf("/") >= 0) {
				dateToken = "/";
			} else if (strDate.indexOf(".") >= 0) {
				dateToken = ".";
			}

			if (strDate.indexOf(":") >= 0) {
				timeToken = ":";
			}

			String date = strDate.toLowerCase().trim();
			int pos = date.indexOf(" ");
			String day = "";
			String time = "";

			if (pos > 0) {
				day = date.substring(0, pos).trim();
				time = date.substring(pos + 1).trim();
			} else if (timeToken != null) {
				time = date.trim();
			} else {
				day = date.trim();
			}

			StringBuilder buf = new StringBuilder();

			if (day.length() > 0) {
				if (dateToken == null) {
					switch (day.length()) {
					case 4:
						buf.append("yyyy");
						break;
					case 5:
						buf.append("yyyyq");
						break;
					case 6:
						buf.append("yyyyMM");
						break;
					case 8:
						buf.append("yyyyMMdd");
					case 7:
					default:
						break;
					}
				} else {
					String[] parseDay = UtilString
							.stringToArray(day, dateToken);

					for (int i = 0; i < parseDay.length; i++) {
						int len = parseDay[i].length();
						if (i == 0) {
							buf.append("yyyy".substring(0, len));
						}

						if (i == 1) {
							if (parseDay.length == 3) {
								if (parseDay[i].length() == 1)
									buf.append("M".substring(0, len));
								else if (parseDay[i].length() == 2)
									buf.append("MM".substring(0, len));

							} else if (parseDay[i].length() == 2) {
								buf.append("MM".substring(0, len));
							} else if (Integer.parseInt(parseDay[i]) <= 4)
								buf.append("q".substring(0, len));
							else {
								buf.append("M".substring(0, len));
							}
						}

						if (i == 2) {
							buf.append("dd".substring(0, len));
						}
						if (i >= parseDay.length - 1)
							continue;
						buf.append(dateToken);
					}
				}

			}

			if (time.length() > 0) {
				buf.append(" ");
				String[] parseTime = UtilString.stringToArray(time, timeToken);
				for (int i = 0; i < parseTime.length; i++) {
					if (i == 0) {
						buf.append("HH".substring(0, parseTime[i].trim()
								.length()));
					}
					if (i == 1) {
						buf.append("mm".substring(0, parseTime[i].trim()
								.length()));
					}
					if (i == 2) {
						pos = parseTime[i].indexOf(".");
						if (pos > 0) {
							String left = parseTime[i].substring(0, pos);

							buf.append("ss".substring(0, left.trim().length()));
							buf.append(".S");
						} else {
							buf.append("ss".substring(0, parseTime[i].trim()
									.length()));
						}
					}

					if (i >= parseTime.length - 1)
						continue;
					buf.append(timeToken);
				}
			}

			return buf.toString().trim();
		} catch (Exception e) {
		}
		return null;
	}

	public static Date getEndWeekDay(Date date) {
		Date dtRet = null;

		GregorianCalendar gc = new GregorianCalendar();
		gc.setTime(date);
		gc.add(5, 6 - gc.get(7));
		dtRet = gc.getTime();

		return dtRet;
	}

	public static Date getFirstWeekDay(Date date) {
		Date dtRet = null;

		GregorianCalendar gc = new GregorianCalendar();
		gc.setTime(date);
		gc.add(5, -1 * (gc.get(7) - 2));
		dtRet = gc.getTime();

		return dtRet;
	}

	public static boolean isDate(String strDate) {
		Date format = toDate(strDate);

		return format != null;
	}

	public static Date relativeDate(Date date, int days) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(5, days);
		return c.getTime();
	}

	public static Date relativeDate(int days) {
		return relativeDate(new Date(), days);
	}

	public static Date relativeMonth(int months) {
		return relativeMonth(new Date(), months);
	}

	public static Date relativeMonth(Date date, int months) {
		GregorianCalendar gc = new GregorianCalendar();
		gc.setTime(date);
		gc.add(2, months);
		return gc.getTime();
	}

	public static Date toDate(String strDate) {
		String format = getDateFormat(strDate);
		if (format == null) {
			return null;
		}
		return toDate(strDate, format);
	}

	public static Date toDate(String strDate, String strFormat) {
		try {
			String[] parts = quarter2month(strDate, strFormat);

			SimpleDateFormat sdf = new SimpleDateFormat(parts[1]);
			return sdf.parse(parts[0]);
		} catch (ParseException e) {
		}
		return null;
	}

	protected static String[] quarter2month(String strDate, String strFormat) {
		if (strFormat.indexOf("-q") > 0) {
			String[] parts = strDate.split("-");
			int month = (Integer.parseInt(parts[1]) - 1) * 3 + 1;

			if (month < 10)
				parts[1] = ("0" + month);
			else {
				parts[1] = month + "";
			}
			strDate = parts[0] + "-" + parts[1];

			parts = strFormat.split("-");
			strFormat = parts[0] + "-MM";
		}

		return new String[] { strDate, strFormat };
	}

	public static java.sql.Date toSqlDate(String strDate) {
		Date utilDate = toDate(strDate);
		if (utilDate == null)
			return null;

		return new java.sql.Date(utilDate.getTime());
	}

	public static java.sql.Date toSqlDate(String strDate, String strFormat) {
		Date utilDate = toDate(strDate, strFormat);
		if (utilDate == null)
			return null;
		return new java.sql.Date(utilDate.getTime());
	}

	public static Timestamp toSqlTimestamp(String strDate) {
		Date utilDate = toDate(strDate);
		if (utilDate == null)
			return null;

		return new Timestamp(utilDate.getTime());
	}

	public static Timestamp toSqlTimestamp(String strDate, String strFormat) {
		Date utilDate = toDate(strDate, strFormat);
		if (utilDate == null)
			return null;
		return new Timestamp(utilDate.getTime());
	}

	public static Date convert(Date date, TimeZone srcTZ,
			TimeZone destTZ) {
		if (srcTZ.equals(destTZ))
			return date;
		Calendar cal1 = (Calendar) Calendar.getInstance().clone();
		cal1.setTimeZone(srcTZ);
		cal1.setTime(date);
		cal1.set(14, 0);
		cal1.setTimeZone(destTZ);
		cal1.set(14, 0);
		return new Timestamp(cal1.getTimeInMillis());
	}

	public static Date string2date(String datastr, String format)
			throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.parse(datastr);
	}

	public static Date dateCutNum(Date dd, int datenum)
			throws ParseException {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar cal = Calendar.getInstance();
		cal.setTime(dd);
		cal.add(Calendar.DATE, -datenum); // 减1天
		return df.parse(df.format(cal.getTime()));
	}

	public static String date2string(Date dd) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return df.format(dd);
	}
	
	public static String dateToStringDay(Date dd) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		return df.format(dd);
	}

	/**
	 * 
	 * @author   name  : wangchao   
	 * @create   time  : 2016-1-19 下午3:43:09 
	 * @method comments: 两个日期相差的天数，到秒级 
	 * @modify   list  : (modify by :modify date:modify content)  
	 * @param fDate
	 * @param oDate
	 * @return
	 * @throws
	 */
	public static int getIntervalDays(Date fDate, Date oDate) {
	       if (null == fDate || null == oDate) {
	           return -1;
	       }
	       long intervalMilli = oDate.getTime() - fDate.getTime();
	       return Integer.parseInt(String.valueOf(intervalMilli / (24 * 60 * 60 * 1000)));

	    }

	/**
	 * 
	 * @author   name  : wangchao   
	 * @create   time  : 2016-1-19 下午3:42:47 
	 * @method comments: 两个日期相差的天数
	 * @modify   list  : (modify by :modify date:modify content)  
	 * @param startDate
	 * @param endDate
	 * @return
	 * @throws
	 */
	public static int daysOfTwo(Date startDate, Date endDate) {
	       Calendar aCalendar = Calendar.getInstance();
	       aCalendar.setTime(startDate);
	       int day1 = aCalendar.get(Calendar.DAY_OF_YEAR);
	       aCalendar.setTime(endDate);
	       int day2 = aCalendar.get(Calendar.DAY_OF_YEAR);
	       return day2 - day1;

	    }
	
	/**
	 *   
	 * @author   name  : wangchao   
	 * @create   time  : 2016-1-27 下午2:11:41 
	 * @method comments: 得到几天前的时间
	 * @modify   list  : (modify by :modify date:modify content)  
	 * @param d
	 * @param day
	 * @return
	 * @throws
	 */
	public static Date getDateBefore(Date d, int day) {         
		Calendar now = Calendar.getInstance();        
		now.setTime(d);         
		now.set(Calendar.DATE, 
		now.get(Calendar.DATE) - day);         
		return now.getTime();     
		}       
	/**
	 *   
	 * @author   name  : wangchao   
	 * @create   time  : 2016-1-27 下午2:11:54 
	 * @method comments: 得到几天后的时间    
	 * @modify   list  : (modify by :modify date:modify content)  
	 * @param d
	 * @param day
	 * @return
	 * @throws
	 */
	public static Date getDateAfter(Date d, int day) {          
		Calendar now = Calendar.getInstance();         
		now.setTime(d);          
		now.set(Calendar.DATE, now.get(Calendar.DATE) + day); 
		return now.getTime();      
	}
	/**
	 * 字符串时间转LONG
	 * @param sdate
	 * @return
	 */
	public static long string2long(String sdate){
		if(sdate.length() < 11){
			sdate = sdate + " 00:00:00";
		}
		SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date dt2 = null;
		try {
			dt2 = sdf.parse(sdate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		//继续转换得到秒数的long型
		long lTime = dt2.getTime() / 1000;
		return lTime;
	}
	
	/**
	 * LONG时间转字符串
	 * @param ldate
	 * @return
	 */
	public static String long2string(long ldate){
		SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//前面的ldate是秒数，先乘1000得到毫秒数，再转为java.util.Date类型
		java.util.Date dt = new Date(ldate * 1000);  
		String sDateTime = sdf.format(dt);  //得到精确到秒的表示
		if(sDateTime.endsWith("00:00:00")){
			sDateTime = sDateTime.substring(0,10);
		}
		return sDateTime;
	}
	
	 public static void main(String[] args) {
		 
		   Date fDate =  new GregorianCalendar(2016, 1, 18,13,14,0).getTime();//new GregorianCalendar().getTime();
	       Date oDate = new GregorianCalendar(2016, 1, 19,13,13,0).getTime();
	       new GregorianCalendar().setTime(new Date());
	       System.out.println("使用 getIntervalDays 相差天数 = " + getIntervalDays(fDate, oDate));
	       System.out.println("使用 daysOfTwo 相差天数 = " + UtilDate.dateToStringDay(UtilDate.relativeDate(new Date(),-7)));

	}
}